package com.example.campuslink.commen.tools

import android.content.Context
import android.provider.MediaStore
import com.example.campuslink.model.ChoiceFilePathData
import com.example.campuslink.model.VideoInfoData

class VideoUtil {
    fun getLocalVideoList(context: Context): List<ChoiceFilePathData> {
        val videoList: MutableList<VideoInfoData> =
            ArrayList<VideoInfoData>()
        val videoPath: MutableList<ChoiceFilePathData> = ArrayList<ChoiceFilePathData>()
        val reserveVideoPath : MutableList<ChoiceFilePathData> = ArrayList<ChoiceFilePathData>()
        val contentResolver = context.contentResolver
        val videoUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
        // 定义要查询返回的列信息
        val projection = arrayOf(
            MediaStore.Video.Media._ID,
            MediaStore.Video.Media.DISPLAY_NAME,
            MediaStore.Video.Media.DATA,
            MediaStore.Video.Media.DURATION,
            MediaStore.Video.Media.SIZE,
            MediaStore.Video.Media.MIME_TYPE
        )
        try {
            contentResolver.query(videoUri, projection, null, null, null).use { cursor ->
                if (cursor != null && cursor.moveToFirst()) {
                    val idIndex = cursor.getColumnIndex(MediaStore.Video.Media._ID)
                    val nameIndex = cursor.getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME)
                    val pathIndex = cursor.getColumnIndex(MediaStore.Video.Media.DATA)
                    val durationIndex = cursor.getColumnIndex(MediaStore.Video.Media.DURATION)
                    val sizeIndex = cursor.getColumnIndex(MediaStore.Video.Media.SIZE)
                    val mimeTypeIndex = cursor.getColumnIndex(MediaStore.Video.Media.MIME_TYPE)
                    do {
                        val videoInfo: VideoInfoData = VideoInfoData()
                        videoInfo.id = cursor.getLong(idIndex)
                        videoInfo.name = cursor.getString(nameIndex)
                        videoInfo.path = cursor.getString(pathIndex)
                        videoInfo.duration = cursor.getLong(durationIndex)
                        videoInfo.size = cursor.getLong(sizeIndex)
                        videoInfo.mimeType = cursor.getString(mimeTypeIndex)
                        videoList.add(videoInfo)
                        videoPath.add(ChoiceFilePathData(cursor.getString(pathIndex),false))
                    } while (cursor.moveToNext())
                }
                for(i in videoPath.indices.reversed()){
                    reserveVideoPath.add(videoPath.get(i))
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return reserveVideoPath
    }
}